from modules.storage.file_store import FileStore


class ConfigMain:
    def __init__(self):
        try:
            self.configs_dict = FileStore('scrapy_main/config/configs.json').read() or {}
        except Exception as e:
            # 在发生异常时进行适当的处理，这里简单地打印错误信息
            print(f"Error during initialization: {e}")
            self.configs_dict = {}

    def get_config(self):
        return self.configs_dict

    def get_config_value_by_key(self, config_key):
        # 使用字典的 get 方法，避免引发 KeyError
        return self.configs_dict.get(config_key, None)

    def set_config_value_by_key(self, config_key, edit_config_value):
        try:
            # 尝试设置不存在的键
            self.configs_dict[config_key] = edit_config_value
        except KeyError as e:
            print(f"KeyError: {e}")

    def save_config(self):
        file = FileStore('scrapy_main/config/configs.json', write_file_mode='w')
        file.write(self.configs_dict)


if __name__ == '__main__':
    config = ConfigMain()
    print(config.get_config())
    print(config.get_config_value_by_key('mongodb'))
